const fs = require('fs');
const path = require('path');
var inquirer = require('inquirer');

// const files = fs.readdirSync('./');

function errorHandler(error) {
  if (error) {
    console.log(error);
    return false;
  }
  console.log('创建成功');
}

function create(type, name) {
  const pagePath = path.join('./', `src/${type}`);
  fs.mkdir(path.join(pagePath, `/${name}`), errorHandler);

  const fileName = name.charAt(0).toUpperCase() + name.slice(1);
  const indexContent = `import ${fileName} from './${fileName}';
export default ${fileName};`;
  const tsxContent = `import React from 'react';

import css from './${fileName}.module.css';
  
const ${fileName}: React.FC = () => {
  return (
    <div>666</div>
  );
}

export default ${fileName};`;

  fs.writeFile(path.join(pagePath, `/${name}/${fileName}.module.css`), '', 'utf8', errorHandler);
  fs.writeFile(path.join(pagePath, `/${name}/index.ts`), indexContent, 'utf8', errorHandler);
  fs.writeFile(path.join(pagePath, `/${name}/${fileName}.tsx`), tsxContent, 'utf8', errorHandler);
}

// create('home');

var typeList = {
  type: 'list',
  name: 'type',
  message: '创建：(页面 | 组件)',
  choices: [
    { name: '页面', value: 'page' },
    { name: '组件', value: 'component' }
  ]
};
var inputName = {
  type: 'input',
  name: 'name',
  message: '名字：',
  validate: function (input) {
    if (!input) {
      return '不能为空';
    }
    return true;
  }
};



inquirer
  .prompt([typeList, inputName])
  .then((con) => {
    // { type: 'page', name: '123' }
    // console.log(con);
    create(con.type, con.name);
  });